<?php

namespace mybackend\controllers\cms;

use Yii;
use mybackend\controllers\BaseController;
use common\services\cms\DirService;
use common\entities\cms\DirEntity;
use common\entities\myhtsq\ActionCode;
use common\services\cms\ArticleService;
use yii\helpers\Html;


class DirController extends BaseController {

    public $layout = '@app/views/cms/layouts/main.php';
    protected $_dirService;

    public function __construct($id, $module, DirService $DirService, $config = []) {
        $this->_dirService = $DirService;
        parent::__construct($id, $module, $config);
    }

    protected function roleAuthRules() {
        return [
            'actions' => ['Index', 'Edit', 'Delete', 'QuickSet'],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'Index' => ActionCode::CMS_DIR_VIEW,
                        'Edit' => ActionCode::CMS_DIR_MOD,
                        'Delete' => ActionCode::CMS_DIR_MOD,
                        'QuickSet' => ActionCode::CMS_DIR_MOD,
                    ]
                ]
            ]
        ];
    }

    public function actionIndex() {
        if (Yii::$app->request->isAjax) {
            $nodeid = intval(Yii::$app->request->get('nodeid', 0));
            $data = [
                'rows' => [],
            ];
            $where = ['parent_id' => $nodeid];
            foreach ($this->_dirService->getDirList($where) as $key => $item) {
                $data['rows'][$key] = [
                    'id' => $item->id,
                    'cell' => [
                        $item->id,
                        $item->code,
                        $item->name,
                        $item->short_desc,
                        $item->sort,
                        $item->status,
                        $item->external_display,
                        $item->depth, //层级
                        $item->parent_id, //父id
                        $item->isLeaf ? 'true' : 'false',
                        'false', //是否展开
                    ]
                ];
            }
            echo json_encode($data);
            return Yii::$app->end();
        }
        return $this->render('index');
    }

    public function actionEdit($id = null) {

        if (empty($id)) {
            $model = new DirEntity();
            $model->loadDefaultValues();
        } else {
            $model = DirEntity::find()->where(['id' => $id])->one();
        }
        if (Yii::$app->request->isPost) {
            $model->setAttributes(Yii::$app->request->post('DirEntity'));
            if ($model->save()) {
                return $this->json(['retCode' => 0]);
            } else {
                $res = json_encode([
                    'retCode' => '-1',
                    'retMsg' => Html::errorSummary($model, ['class' => 'errorSummary'
                    ])]);
                return Html::script('top.postCallback(' . $res . ')');
            }
        }
        $data = [
            'model' => $model,
            'dirs' => DirEntity::getEditDirList(),
            'charsets' => DirEntity::getEnumOption()
        ];
        return $this->json([
            'retCode' => '0',
            'data' => $data
        ]);
    }

    public function actionDelete() {
        if (Yii::$app->request->isAjax) {
            $ids = explode(',', Yii::$app->request->post('id'));
            foreach ($ids as $id) {
                if ($this->_dirService->existsDir($id)) {
                    echo json_encode(['status' => false, 'errMsg' => '目录存在子目录，删除失败！']);
                }else{
                    if(ArticleService::existsArticleByDirId($id)){
                        echo json_encode(['status' => false, 'errMsg' => '目录下有文章，删除失败！']);
                    }else{
                        DirEntity::find()->where(['id' => $id])->one()->delete();
                    }
                }
            }

        }
    }

    public function actionQuickSet() {
        $id = $_POST['id'];
        unset($_POST['id']);
        unset($_POST['oper']);
        $model = DirEntity::find()->where(['id' => $id])->one();
        if (!$model) {
            echo json_encode(['status' => false, 'errMsg' => \common\error\ErrorMsg::getDefaultMsg()]);
            return Yii::$app->end();
        }

        if (isset($_POST['external_display'])) {
            $this->_dirService->displaySet($id, $_POST['external_display']);
        }

        $model->setAttributes($_POST);
        $content = '';
        if (!$model->save()) {
            foreach ($model->getErrors() as $errors) {
                foreach ($errors as $error) {
                    if ($error != '')
                        $content.="{$error}";
                }
            }
            echo json_encode(['status' => false, 'errMsg' => $error]);
            return Yii::$app->end();
        }
    }

    public function actionTest() {
        print_r(DirEntity::getDir());
    }

}
